#include <common.h>
#include <isr.h>
#include <monitor.h>
#include <drivers/mouse.h>
#include <Starflub/Starflub.h>

byte mouse_cycle=0;
int mouse_byte[3];
int mouse_x = 0;
int mouse_y = 0;

void mouse_handler(registers_t regs) {
	switch(mouse_cycle) {
		case 0:
		case 1:
			mouse_byte[mouse_cycle] = inb(0x60);
			mouse_cycle++;
			break;
		case 2:
			mouse_byte[2] = inb(0x60);
			mouse_x = mouse_byte[1];
			mouse_y = mouse_byte[2];
			mouse_cycle=0;
			break;
	}
}

inline void mouse_wait(byte a_type) {
	dword _time_out = 100000;
	if(a_type == 0)
		while(_time_out--)
			if((inb(0x64)&1) == 1)
				return;
	else
		while(_time_out--)
			if((inb(0x64)&2) == 0)
				return;
	return;
}

inline void mouse_write(byte a_write) {
	mouse_wait(1);
	outb(0x64, 0xD4);
	mouse_wait(1);
	outb(0x60, a_write);
}

byte mouse_read() {
	mouse_wait(0);
	return inb(0x60);
}

void mouse_install() {
	byte _status;
	mouse_wait(1);
	outb(0x64, 0xA8);
	
	mouse_wait(1);
	outb(0x64, 0x20);
	mouse_wait(0);
	_status = (inb(0x60)|2);
	mouse_wait(1);
	outb(0x64, 0x60);
	mouse_wait(1);
	outb(0x60, _status);
	
	mouse_write(0xF6);
	mouse_read();
	
	mouse_write(0xF4);
	mouse_read();
	
	register_interrupt_handler(IRQ12, &mouse_handler);
}

